package com.dailyblue.java.project.power.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.power.bean.Users;
import com.dailyblue.java.project.power.service.UsersService;
import com.dailyblue.java.project.power.util.ResultCode;
import com.dailyblue.java.project.power.util.ResultTool;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class HavePermissionInterceptor implements HandlerInterceptor {
    @Resource
    private UsersService usersService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean b = (boolean) request.getAttribute("AAA");
        System.out.println("进入了权限校验，b:" + b);
        if (b) {
            return true;
        }
        String uri = request.getRequestURI();
        int index = uri.indexOf("/", 1);
        uri = uri.substring(index);
        String token = request.getHeader("token");
        Users obj = (Users) request.getSession().getServletContext().getAttribute(token);
        int count = usersService.checkUsersHasPermission(obj.getId(), uri);
        if (count == 0) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONArray.toJSONString(ResultTool.fail(ResultCode.NO_PERMISSION)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
